package com.baidu.ai.aip.utils;



import com.baidu.ai.aip.domain.AiToken;
import com.baidu.ai.aip.service.BaiduService;
import com.baidu.ai.aip.service.impl.BaiduServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Access token默认有效期为30天
 * @author 张立民
 * @Date 2024/02/27
 * @described 获取百度token
 *
 *
 *
 * 百度AI开放平台使用OAuth2.0授权调用开放API，调用API时必须在URL中带上Access_token参数，Access token默认有效期为30天，获取Access_token的流程如下：
 *
 * 请求URL数据格式
 * 向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求（推荐使用POST），并在URL中带上以下参数：
 *
 * grant_type： 必须参数，固定为client_credentials；
 * client_id： 必须参数，应用的API Key；
 * client_secret： 必须参数，应用的Secret Key；
 *
 */
public class GetToken {

   /* static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    static final String tokenUrl = "https://aip.baidubce.com/oauth/2.0/token";
    static final String grant_type = "client_credentials";
    static final String clientId = "OX3aXqXxP7q3r75AHf7qpy8s";
    static final String clientSecret = "QmZoi3guCS9BvLVGphYVlmZIPEI59q6A";

    @Autowired
    private  BaiduService baiduService;

    public String getToken() {
        final String tokens = baiduService.getToken();
        Date dateNow = DateUtils.getNowDate();
        if(tokens != null && tokens.size()  >0){
            *//**
             * 获取当生成时间
             * 获取有效天数
             * 获取当前时间
             * 生成时间+有效时间< 当前时间有效，否则重新获取
             *//*
            AiToken token = tokens.get(0);

            final Date applyDate = token.getApplyDate();
            final int daysDiff = DateUtils.differentDaysByMillisecond(dateNow, applyDate);
            if(daysDiff > 0){
                return token.getToken();
            }else{
                final Map tokenFromBaidu = getTokenFromBaidu();
                final int id = token.getId();
                final long expiresInDays = DateUtils.convertsecondsToDays(Long.parseLong(tokenFromBaidu.get("expires_in").toString()));
                final String accessToken = tokenFromBaidu.get("access_token").toString();
                int i = baiduService.updateToken(dateNow,accessToken,expiresInDays,id);
                return accessToken;
            }
        }else {
            final Map tokenFromBaidu = getTokenFromBaidu();
            final long expiresInDays = DateUtils.convertsecondsToDays(Long.parseLong(tokenFromBaidu.get("expires_in").toString()));
            final String accessToken = tokenFromBaidu.get("access_token").toString();
            int i = baiduService.insertToken(dateNow,accessToken,expiresInDays);
            return accessToken;
        }

    }

    private static Map getTokenFromBaidu()  {
        StringBuffer sb = new StringBuffer();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url(sb.append(tokenUrl)
                        .append("?client_id=")
                        .append(clientId)
                        .append("&client_secret=")
                        .append(clientSecret)
                        .append( "&grant_type=client_credentials").toString())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
        } catch (IOException e) {
            System.out.println("###########从百度获取token失败！");
            e.printStackTrace();
        }

        //response.body().string()
        final Map map = GsonUtils.fromJson(response.body().toString(), Map.class);
        return map;
    }












    *//*public static void main(String []args) throws IOException{
        StringBuffer sb = new StringBuffer();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url(sb.append(tokenUrl)
                        .append("?client_id=")
                        .append(clientId)
                        .append("&client_secret=")
                        .append(clientSecret)
                        .append( "&grant_type=client_credentials").toString())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        System.out.println(response.body().string());

    }

     */
}
